package com.enseirb.bdxmap.dao.webrequest;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;

import utils.BdxMapApplication;
import utils.InputStreamUtil;
import android.content.Context;

import com.enseirb.bdxmap.R;
import com.enseirb.bdxmap.exception.BdxMapException;

public class WebServiceRequestManager {
	
	private static final String HTTP_GET_METHOD = "GET";
	private static final int READ_TIMEOUT = 5000;
	private static final int CONNECTION_TIMEOUT = 5000;
	private ConnectionDetector connectionDetector;

	public String request(String url) throws BdxMapException
	{
		Context context = BdxMapApplication.getAppContext();
		connectionDetector = new ConnectionDetector(context);
		if(!connectionDetector.isConnected()) {
			throw new BdxMapException(context != null ? context.getResources().getString(R.string.verify_internet) : new String());
		}
		
		String result = "";
		InputStream input = null;
		try {
			input = connectTo(url);
			result = InputStreamUtil.readInputStream(input);
			return result;
		} catch(MalformedURLException e){
			e.printStackTrace();
		} catch(IOException e){
			System.err.println(e);
		} finally {
			InputStreamUtil.closeInputStream(input);
		}
		return "";
	}
	
	private InputStream connectTo(String urltoparse) throws MalformedURLException, IOException, ProtocolException
	{
		URL url = new URL(urltoparse);
		HttpURLConnection connection = (HttpURLConnection) url.openConnection();
		connection.setReadTimeout(READ_TIMEOUT);
		connection.setConnectTimeout(CONNECTION_TIMEOUT);
		connection.setRequestMethod(HTTP_GET_METHOD);
		connection.setDoInput(true);
		connection.connect();
		InputStream input = connection.getInputStream();
		return input;
	}
}
